<template>
  <a-form :form="form">
    <a-form-item label="类别"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-radio-group name="radioGroup" :disabled="unit.type===0||unit.type===1" v-model="type">
        <a-radio :value="0">
          前台类目
        </a-radio>
        <a-radio :value="1">
          后台类目
        </a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
        label="类目名称"
    >
      <a-input
          v-decorator="[
          'unit.title',
          { rules: [{ required: true, message: '请输入' }] },
        ]"
          placeholder="请输入"
      />
    </a-form-item>
    <a-form-item
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
        label="副标题"
    >
      <a-input
          v-decorator="[
          'unit.subTitle',
          { rules: [{ required: false, message: '请输入' }] },
        ]"
          placeholder="请输入"
      />
    </a-form-item>
    <a-form-item label="关联后台类目"
                 v-show="type===0"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-select
          mode="multiple"
          :size="size"
          placeholder="可输入多个品牌"
          style="width: 100%"
          v-decorator="[
          'unit.relateCategory',
          { rules: [{ required: false, message: '请输入' }] },
        ]"
      >
        <a-select-option v-for="item in categoryList" :key="item.value" :value="item.value" >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="品牌"
                 v-show="type===1"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-select
          mode="multiple"
          :size="size"
          placeholder="可输入多个品牌"
          style="width: 100%"
          v-decorator="[
          'unit.brandIds',
          { rules: [{ required: false, message: '请输入' }] },
        ]"
      >
        <a-select-option v-for="item in brandList" :key="item.value" :value="item.value" >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="销售属性"
                 :label-col="formItemLayout.labelCol"
                 v-show="type===1"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-select
          mode="multiple"
          :size="size"
          placeholder="可输入多个"
          style="width: 100%"
          v-decorator="[
          'unit.specIds',
          { rules: [{ required: false, message: '请输入' }] },
        ]"
      >
        <a-select-option v-for="item in specList" :key="item.value" :value="item.value" >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="类目图片"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-upload
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadApi"
          :headers="{Authorization: `Bearer ${token}`}"
          :before-upload="beforeUpload"
          @change="handleChange"
          :disabled="loading"
          v-decorator="[
          'unit.image',
          { rules: [{ required: false, message: '请上传' }] },
        ]"
      >
        <img v-if="unit.image" :src="unit.image" alt="avatar" class="img-up"/>
        <div v-else>
          <a-icon :type="loading ? 'loading' : 'plus'" />
          <div class="ant-upload-text"></div>
        </div>
      </a-upload>
    </a-form-item>

    <a-form-item label="排序"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-input-number id="inputNumber" :min="0" @change="onChange" v-decorator="[
          'unit.sorts',{ initialValue: 0 },
        ]" />
    </a-form-item>
    <a-form-item label="状态"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-radio-group name="radioGroup"  v-decorator="[
          'unit.status', { rules: [{ required: true, type: 'number', message:'请选择',initialValue: 0 }]} ]">
        <a-radio :value="0">
          启用
        </a-radio>
        <a-radio :value="1">
          禁用
        </a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="自然属性"
                 v-if="type===1"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-button type="dashed" @click="addBtn">
        +添加
      </a-button>
    </a-form-item>
    <a-form-item label="自然属性"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol"
                 v-for="(item,index) in attributeList"
                 :key="index"
    >
      <a-row>
        <a-col :span="8">
          <a-input  v-model="item.name"></a-input>
        </a-col>
        <a-col :span="1">
        </a-col>

        <a-col :span="13">
          <a-form-item>
            <a-select
                v-model="item.options"
                mode="tags"
                :size="size"
                placeholder="请输入"
                style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="1">
        </a-col>
        <a-col :span="1">
          <a-icon type="minus-circle" @click="delBtn(index)" />
        </a-col>
      </a-row>
    </a-form-item>
    <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol">
      <a-button type="primary" @click="check">
        提交
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import code from '@/common/code'
import {getBrandList, getCategoryDetail,getSpecList,editCategory,getTwoLevelCategoryList} from '@/api'
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 8 },
};
const formTailLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 8, offset: 4 },
};
export default {
  name: "brand-edit",
  data() {
    return {
      brandList:[],
      specList:[],
      attributeList:[],
      categoryList:[],
      unit:{},
      token:localStorage.getItem('token')||'',
      uploadApi: '/admin-api/common/uploadFile',
      loading: false,
      imageUrl: '',
      value: 1,
      type: null,
      size:'default',
      formItemLayout,
      formTailLayout,
      form: this.$form.createForm(this, { name: 'dynamic_rule' }),
    };
  },
  methods: {
    addBtn(){
      this.attributeList.push({})
    },
    delBtn(index){
      this.attributeList.splice(index,1)
      // this.attributeList=[...this.attributeList.slice(0,index),...this.attributeList.slice(index+1)]
    },
    onChange(value) {
    },
    //提交
    check() {
      this.form.validateFields(async (err,values)=> {
        if (!err) {
          if (this.$route.query.id) {
            values.unit.id = this.$route.query.id
          }
          if(this.attributeList.length>0){
            this.attributeList.forEach((item,index)=>{
              this.unit.attributeList[index].name=item.name
              this.unit.attributeList[index].options=JSON.stringify(item.options)
            })
          }

          values.unit.type=this.type;
          values.unit.attributeList=this.unit.attributeList;
          console.log('values',values.unit)
          await editCategory(values.unit)
          this.$message.success('操作成功')
          this.$router.push('/shop/category-list')
        }
      });
    },
    handleChange (e) {
      if (e.file.status === 'done') {
        if (e.file.response.code === code.SUCCESS) {
          this.unit.image = e.file.response.value
          // this.$emit('change', this.imageUrl)
        } else {
          this.$message.error(e.file.response.message)
        }
        this.loading = false
      }

    },
    beforeUpload (file) {
      this.loading = true
      const the = this
      return new Promise((resolve, reject) => {
        const url = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function () {
          const { width, height } = img
          the.loading = false
          // 校验格式
          if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            the.$message.error('请上传JPG,PNG格式')
            reject(false)
          }

          // 校验大小
          if (file.size > this.maxSize * 1024 * 1024) {
            the.$message.error(`不得大于${this.maxSize}M`)
            reject(false)
          }

          // 校验比例
          if (the.proportion && ratio(width, height).toString() !== the.proportion) {
            the.$message.error('图片比例不正确')
            reject(false)
          }

          // 校验尺寸
          if ((the.fixedWidth && the.fixedWidth !== width) || (the.fixedHeight && the.fixedHeight !== height)) {
            the.$message.error('图片尺寸不正确')
            reject(false)
          }
          resolve(file)
        }
        img.src = url.createObjectURL(file)
      })
    },
    //品牌详情
    async getBrandDetailFn(){
     const res1= await getCategoryDetail(this.$route.query.id)
      const res2= await getBrandList()
      const res3= await getSpecList()
      const res4= await getTwoLevelCategoryList(0)
      this.brandList=res2.value.map(item=> {
        return {
          value: item.id,
          label: item.name
        }
      })
      this.specList=res3.value.map(item=> {
        return {
          value: item.id,
          label: item.name
        }
      })
this.categoryList=res4.value.map(item=>{
  return{
    value: item.id,
    label: item.title
  }
})
      this.unit=res1.value
      this.type=this.unit.type;
      //
      // this.attributeList=(this.unit.attributeList||[]).map(item=>{
      //   return {
      //     name:item.name,
      //     options:JSON.parse(item.options)
      //   }
      // })
    if(this.unit.attributeList && this.unit.attributeList.length>0){
      this.attributeList=this.unit.attributeList.map(item=>{
        return {
          name:item.name,
          options:JSON.parse(item.options)
        }
      })
    }
      this.form.setFieldsValue({
        'unit.title': this.unit.title,
        'unit.sorts': this.unit.sorts,
        'unit.status': this.unit.status,
        'unit.image': this.unit.image,
        'unit.brandIds': this.unit.brandIds,
        'unit.specIds': this.unit.specIds,
        'unit.relateCategory': this.unit.relateCategory,
        'unit.subTitle': JSON.parse(this.unit.extension).subTitle,
      });
    }
  },
  mounted(){

    if(this.$route.query.id){
      this.getBrandDetailFn()

    }

  }
};
</script>


<style scoped lang="less">

.img-up{
  width: 100%;
  height: 100%;
}
</style>
